//SPDX-FileCopyrightText: Copyright 2022-2024 深圳市同心圆网络有限公司
//SPDX-License-Identifier: GPL-3.0-only

import React, { useEffect, useState } from "react";
import { list_repo_branch, LocalRepoBranchInfo, LocalRepoTagInfo, type LocalRepoInfo, type HeadInfo, list_repo_tag } from "@/api/local_repo";
import { Form, message, Modal, Select } from "antd";
import { checkout, run_status } from "@/api/git_wrap";
import { WebviewWindow } from '@tauri-apps/api/window';
import type * as NoticeType from '@/api/notice_type';


export interface ChangeBranchOrTagModalProps {
    headInfo: HeadInfo;
    repo: LocalRepoInfo;
    onCancel: () => void;
    onOk: () => void;
}

const ChangeBranchOrTagModal = (props: ChangeBranchOrTagModalProps) => {
    const oldTarget = props.headInfo.detached ? props.headInfo.tag_name : props.headInfo.branch_name

    const [curTarget, setCurTarget] = useState(oldTarget);

    const [branchList, setBranchList] = useState<LocalRepoBranchInfo[]>([]);
    const [tagList, setTagList] = useState<LocalRepoTagInfo[]>([]);

    const loadBranchList = async () => {
        const localList = await list_repo_branch(props.repo.path);
        const remoteList = await list_repo_branch(props.repo.path, true);
        for (const branch of remoteList) {
            if (branch.name.startsWith("origin/") == false) {
                continue;
            }
            const name = branch.name.substring("origin/".length);
            if (name == "HEAD") {
                continue;
            }
            if (localList.map(item => item.name).includes(name)) {
                continue;
            }
            localList.push({
                name: name,
                upstream: branch.name,
                commit_id: branch.commit_id,
                commit_summary: branch.commit_summary,
                commit_time: branch.commit_time,
            });
        }
        setBranchList(localList);
    };

    const loadTagList = async () => {
        const res = await list_repo_tag(props.repo.path);
        setTagList(res);
    };

    const checkOutBranchOrTag = async () => {
        const statusList = await run_status(props.repo.path);
        if (statusList.length > 0) {
            message.warn("本地有文件修改未提交，请先提交文件");
            return;
        }
        await checkout(props.repo.path, curTarget);
        props.onOk();
        message.info("切换成功");
        const webView = WebviewWindow.getByLabel("main");
        if (webView != null) {
            const notice: NoticeType.AllNotice = {
                ClientNotice: {
                    LocalRepoChangeNotice: {
                        repoId: props.repo.id,
                    },
                },
            };
            webView.emit("notice", notice);
        }
    };

    useEffect(() => {
        loadBranchList();
        loadTagList();
    }, []);

    return ( 
        <Modal open title={`仓库 ${props.repo.name} 切换分支`} mask={false}
            okText="切换" okButtonProps={{ disabled: curTarget == oldTarget }}
            onCancel={e => {
                e.stopPropagation();
                e.preventDefault();
                props.onOk();
            }}
            onOk={e => {
                e.stopPropagation();
                e.preventDefault();
                checkOutBranchOrTag();
            }}>
            <Form>
                <Form.Item label="分支/标记">
                    <Select value={curTarget} onChange={value => setCurTarget(value)}
                        options={[
                            {
                                label: "分支",
                                options: branchList.map(item => ({
                                    label: item.name,
                                    value: item.name,
                                })),
                            },
                            {
                                label: "标记",
                                options: tagList.map(item => ({
                                    label: item.name,
                                    value: item.name,
                                })),
                            }
                        ]} />

                </Form.Item>
            </Form>
        </Modal>
    )
};

export default ChangeBranchOrTagModal;